<?php
/**
 * 支付回调
 *
 *
 *
 *
 * by 33hao.com 好商城V3 运营版
 */
//支付返回的URL
//http://www.gxxwkj.cn/shop/mobile/api/payment/alipay/call_back_url.php?
//out_trade_no=660539972479327185-r&request_token=requestToken&result=success&trade_no=2017020921001004000210194653&sign=6d46cd97b70438b18cbc0f0ce707738c&sign_type=MD5
//use Shopnc\Tpl;

defined('InShopNC') or exit('Access Invalid!');

class paymentControl extends mobileHomeControl{

    private $payment_code;


	public function __construct() {
		parent::__construct();
        $this->payment_code = $_GET['payment_code'];
        
	}

    public function returnopenidOp(){
        $payment_api = $this->_get_payment_api();
        if($this->payment_code != 'wxpay'){
            output_error('支付参数异常');
            die;
        }

        $payment_api->getopenid();

    }

    /**
     * 支付回调
     */
    public function returnOp() {
        unset($_GET['act']);
        unset($_GET['op']);
        unset($_GET['payment_code']);

        $payment_api = $this->_get_payment_api();

        $payment_config = $this->_get_payment_config();

        $callback_info = $payment_api->getReturnInfo($payment_config);

        if($callback_info) {
            //验证成功
            $result = $this->_update_order($callback_info['out_trade_no'], $callback_info['trade_no']);
            if($result['state']) {
                Tpl::output('result', 'success');
                Tpl::output('message', '支付成功');
            } else {
                Tpl::output('result', 'fail');
                Tpl::output('message', '支付失败');
			}
        } else {
			//验证失败
            Tpl::output('result', 'fail');
            Tpl::output('message', '支付失败');
		}

        Tpl::showpage('payment_message');
    }
    
    /**
     * 支付回调
     */
    public function bestpay_returnOp() {
        unset($_GET['act']);
        unset($_GET['op']);
        unset($_GET['payment_code']);

        $payment_api = $this->_get_payment_api();

        $payment_config = $this->_get_payment_config();

        $callback_info = $payment_api->getReturnInfo($payment_config);

        if($callback_info) {
            //验证成功
            $result = $this->_update_order($callback_info['orderSeq'], $callback_info['orderSeq']);
            if($result['state']) {
                Tpl::output('result', 'success');
                Tpl::output('message', '支付成功');
            } else {
                Tpl::output('result', 'fail');
                Tpl::output('message', '支付失败');
			}
        } else {
			//验证失败
            Tpl::output('result', 'fail');
            Tpl::output('message', '支付失败');
		}

        Tpl::showpage('payment_message');
    }

    /**
     * 支付提醒
     */
    public function notifyOp() {
        // 恢复框架编码的post值
        $_POST['notify_data'] = html_entity_decode($_POST['notify_data']);

        $payment_api = $this->_get_payment_api();

        $payment_config = $this->_get_payment_config();

        $callback_info = $payment_api->getNotifyInfo($payment_config);

        if($callback_info) {
            //验证成功
            $result = $this->_update_order($callback_info['out_trade_no'], $callback_info['trade_no']);
            if($result['state']) {
                if($this->payment_code == 'wxpay'){
                    echo $callback_info['returnXml'];
                    die;
                }else{
                    echo 'success';die;
                }

            }
		}

        //验证失败

        if($this->payment_code == 'wxpay'){
            echo '<xml><return_code><!--[CDATA[FAIL]]--></return_code></xml>';
            die;
        }else{
            echo "fail";die;
        }
    }

    /**
     * 获取支付接口实例
     */
    private function _get_payment_api() {
        $inc_file = BASE_PATH.DS.'api'.DS.'payment'.DS.$this->payment_code.DS.$this->payment_code.'.php';

        if(is_file($inc_file)) {
            require($inc_file);
        }

        $payment_api = new $this->payment_code();

        return $payment_api;
    }

    /**
     * 获取支付接口信息
     */
    private function _get_payment_config() {
        $model_mb_payment = Model('mb_payment');

        //读取接口配置信息
        $condition = array();
        $condition['payment_code'] = $this->payment_code;
        $payment_info = $model_mb_payment->getMbPaymentOpenInfo($condition);
        
        return $payment_info['payment_config'];
    }

    /**
     * 更新订单状态
     * 如果是拼团，同时改变拼团支付状态
     */
    private function _update_order($out_trade_no, $trade_no) {
        //支付成功调用的页面，在这里可以查找对应的
        //把拼团信息从这里写入2017-01-23S
        //更新拼团或者参团$out_trade_no=>pay_sn
        $order_model=Model('order');
        $dondition_or['pay_sn']=$out_trade_no;
        $order_info=$order_model->getOrderInfo($dondition_or);
        //保存用户购买成功操作
        $order_id=$order_info['order_id'];
        
        //得到team_id=$order_info['team_id'],找到该用户， //订单已经支付为20
        if ($order_info['team_id'] !=0 && $order_info['order_state'] < 20){
            //先验证团长
            $condition_mem['member_id']=$condition_team['lead_id']=$order_info['buyer_id'];
            $condition_mem['team_id']=$condition_team['team_id']=$order_info['team_id'];
            $update['pay_status']=1;
            $groupbuy_team_model=Model('groupbuy_team');
            $groupbuy_mem_model=Model('groupbuy_mem');
            
            //$condition_mem['member_id']=$condition_team['lead_id'];
            //$condition_mem['team_id']=$condition_team['team_id'];
            //先检查有没有这个团长的拼团
            $check_info=$groupbuy_team_model->check_team($condition_team);
            if (!empty($check_info)){
                $result_team=$groupbuy_team_model->update_team($check_info['team_id']);
                //在拼团成员表也操作一遍
                $result_mem=$groupbuy_mem_model->update_mem($condition_mem,$update);
            }else{
                //成员表
                $groupbuy_team_model->update_mem_team($order_info['team_id']);
                $groupbuy_mem_model->update_mem($condition_mem,$update);
            }
            //获取拼团信息
            $con_team['team_id']=$order_info['team_id'];
            /* $group['groupbuy_id']=$check_info['groupbuy_id'];
            $group_model=Model('groupbuy');
            $groupbuy_info=$group_model->getGroupbuyOnlineInfo($group); */
            //找到对应的拼团
            $team_info=$groupbuy_team_model->groupbuy_team_info($con_team);
            if($team_info['team_number']>=$team_info['record_num']){
                //成团
                $con_mem['team_id']=$con_team['team_id'];
                $con_mem['pay_status']=1;
                $mem_list=$groupbuy_mem_model->member_list($con_mem);
                foreach ($mem_list as $key =>$val){
                    
                    $mobile = $val['buyer_name'];
                    //要提供三个参数
                    $data['buyer_name']=$mobile;
                    $data['team_id']=$con_mem['team_id'];
                    //个性化短信
                    $result=$this->_testSms($data);
                    if(!$result){
                        echo '消息未发出<br>';
                        //output_data(array('status'=>'error','msg'=>'消息未发出'));
                    }
                    
                }
            }
        }
        //把拼团信息从这里写入2017-01-23 E

        $model_order = Model('order');
        $logic_payment = Logic('payment');

        $tmp = explode('|', $out_trade_no);
        $out_trade_no = $tmp[0];
        if (!empty($tmp[1])) {
            $order_type = $tmp[1];
        } else {
            $order_pay_info = Model('order')->getOrderPayInfo(array('pay_sn'=> $out_trade_no));
            if(empty($order_pay_info)){
                $order_type = 'v';
            } else {
                $order_type = 'r';
            }
        }

        if ($order_type == 'r') {
            $result = $logic_payment->getRealOrderInfo($out_trade_no);
            if (intval($result['data']['api_pay_state'])) {
                return array('state'=>true);
            }
            $order_list = $result['data']['order_list'];
            $result = $logic_payment->updateRealOrder($out_trade_no, $this->payment_code, $order_list, $trade_no);
            //查找商品信息,保存商品热度
            $con['order_id']=$order_id;
            $member_id=$order_info['buyer_id'];
            $model_member=Model('member');
            $member_info=$model_member->getMemberInfoByID($member_id);
            $order_goods=$model_order->getOrderGoodsList($con);
            foreach ($order_goods as $goods){
                $data['fever_goodsid']=$goods['goods_id'];
                $data['fever_goodsname']=$_POST['goods_name'];
                $data['fever_goodsprice']=$_POST['goods_price'];
                $data['fever_actid']='';
                $data['fever_acttype']='';
                $data['fever_actname']='';
                $data['fever_actiontype']=5;
                $data['fever_actiontime']=TIMESTAMP;
                $data['client']='';
                $data['fever_actionmobile']=$member_info['member_mobile'];
                $model_fever=Model('fever');
                $result=$model_fever->saveFever($data);
            }
            
            foreach ($order_list as $order_info) {
                if($order_info['exchange_state'] == 1) {
                    $userCode = $order_info['buyer_name'];
                    $recordId = $order_info['recordId'];
                    $data = array('userCode' => $userCode,'recordId' => $recordId);
                    $post_data = json_encode($data);
                    $url = 'http://120.76.77.72/open/exchangeGifts';
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                    curl_setopt($ch, CURLOPT_POST, 1); // 启用POST提交
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
                    $result = json_decode(curl_exec($ch));
                }
            }
        } elseif ($order_type == 'v') {
        	$result = $logic_payment->getVrOrderInfo($out_trade_no);
	        if ($result['data']['order_state'] != ORDER_STATE_NEW) {
	            return array('state'=>true);
	        }
	        $result = $logic_payment->updateVrOrder($out_trade_no, $this->payment_code, $result['data'], $trade_no);
        }

        return $result;
    }
    
    /*
     * 发送短信
     */
    private function _testSms($data){
        //echo json_encode($data);die;
        $sms = new Sms();    
        $mobile = $data['buyer_name'];
        $content = '【乐相随】亲爱的'.$data['buyer_name'].'用户，您参与的拼团（拼团id号：'.$data['team_id'].'）成功拼团，商家会尽快给您发货';
        $result = $sms->send($mobile,$content);
        return $result;
    }
	
	/**
     * 支付回调
     */
    public function wxpayreturnOp() {
        unset($_GET['act']);
        unset($_GET['op']);
        unset($_GET['payment_code']);

        $result_code= $_GET['result_code'] ;
        $out_trade_no=$_GET['out_trade_no'] ;
        $transaction_id=$_GET['transaction_id'] ;

        if($result_code == "FAIL"){
            Tpl::output('result', 'fail');
            Tpl::output('message', '支付失败');
        }
        else {
            //验证成功
            $result = $this->_update_order($out_trade_no, $transaction_id);
            if ($result['state']) {
                //更新订单操作
                
                Tpl::output('result', 'success');
                Tpl::output('message', '支付成功');
            } else {
                Tpl::output('result', 'fail');
                Tpl::output('message', '支付失败');
            }
        }

        Tpl::showpage('payment_message');
    }
	
    /**
     * 微信支付提醒
     */
    public function wxpaynotifyOp() {
        // 恢复框架编码的post值
        $result_code= $_GET['result_code'] ;
        $out_trade_no=$_GET['out_trade_no'] ;
        $transaction_id=$_GET['transaction_id'] ;

        if($result_code!= "FAIL") {
            //验证成功
            $result = $this->_update_order($out_trade_no, $transaction_id);
            if($result['state']) {
                echo 'success';die;
            }
        }

        //验证失败
        echo "fail";die;
    }


/**
     * 支付回调
     */
    public function acpayreturnOp() {

        unset($_GET['act']);
        unset($_GET['op']);
        unset($_GET['payment_code']);

        $result_code= $_GET['result_code'] ;
        $out_trade_no=$_GET['out_trade_no'] ;
        $transaction_id=$_GET['transaction_id'] ;

        if($result_code == "00"){
            //验证成功
            $result = $this->_update_order($out_trade_no, $transaction_id);
            if ($result['state']) {
                Tpl::output('result', 'success');
                Tpl::output('message', '支付成功');
            } else {
                Tpl::output('result', 'fail');
                Tpl::output('message', '支付失败');
            }
           
        }
        else {
             Tpl::output('result', 'fail');
            Tpl::output('message', '支付失败');
        }

        Tpl::showpage('payment_message');
    }
}
